//
//  UTSNetworkLibUtils.swift
//  UTSNetworkLib
//
//  Created by Admin on 2024/8/5.
//

import Foundation
import Alamofire


public func getDesition(fileDir: String?, fileName: String?)-> DownloadRequest.Destination? {
    let destination: DownloadRequest.Destination? = { (temporaryURL: URL, response: HTTPURLResponse) in
        var fileURL = temporaryURL
        if let dir = fileDir, let name = fileName {
            var dirStr = dir
            if dirStr.hasSuffix("/") {
                dirStr = String(dirStr[dirStr.startIndex..<dirStr.index(dirStr.endIndex, offsetBy: -1)])
            }
           
            fileURL = URL(fileURLWithPath: "\(dirStr)/\(name)")
        } else if let name = fileName {
            var dirStr = temporaryURL.deletingLastPathComponent().absoluteString
            let endStr = "file://"
            if dirStr.hasPrefix(endStr) {
                dirStr = String(dirStr[dirStr.index(dirStr.startIndex, offsetBy: endStr.count)..<dirStr.endIndex])
            }
            fileURL = URL(fileURLWithPath: "\(dirStr)/\(name)")
        } else if let dir = fileDir {
            var dirStr = dir
            if dirStr.hasSuffix("/") {
                dirStr = String(dirStr[dirStr.startIndex..<dirStr.index(dirStr.endIndex, offsetBy: -1)])
            }
            if let suggestedFilename = response.suggestedFilename {
                fileURL = URL(fileURLWithPath: "\(dirStr)/\(suggestedFilename)")
            }
        } else if let suggestedFilename = response.suggestedFilename {
            var dirStr = temporaryURL.deletingLastPathComponent().absoluteString
            let endStr = "file://"
            if dirStr.hasPrefix(endStr) {
                dirStr = String(dirStr[dirStr.index(dirStr.startIndex, offsetBy: endStr.count)..<dirStr.endIndex])
            }
            fileURL = URL(fileURLWithPath: "\(dirStr)/\(suggestedFilename)")
        }
        let option: DownloadRequest.Options = [.removePreviousFile, .createIntermediateDirectories]
        return (fileURL, option)
    }
    return destination
}


func test() {
 getDesition(fileDir: "", fileName: "")
}
